<template>
  <!--物资管理-物资列表-->
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="21">
          <a-col :xl="5" :lg="9" :md="11" :sm="24">
            <a-form-item label="物资名称">
              <a-input placeholder="请输入物资名称" class="input1" v-model="queryParam.platformProductName" style="width: 100%;"  @input="tolink('input_platformProductName',$event)"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="5" :lg="8" :md="11" :sm="24">
            <a-form-item label="型号">
              <a-input placeholder="请输入型号" class="input1" v-model="queryParam.model" style="width: 100%;"  @input="tolink('input_model',$event)"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="5" :lg="8" :md="11" :sm="24">
            <a-form-item label="仓库">
              <a-input placeholder="请输入仓库" class="input1" v-model="queryParam.warehouseName" style="width: 100%;" @input="tolink('input_warehouseName',$event)"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="5" :lg="8" :md="11" :sm="24">
            <a-form-item label="项目">
              <a-select placeholder="请输入项目" :value="queryParam.projectName"
                @change="handleChange('project',$event)">
                <a-select-option v-for="(item,index) in levelOneOptions" :key="index" :value="item">
                  {{item.label}}
                </a-select-option>
              </a-select>
              <!-- <a-form-item label="项目">
                <a-select :options="levelOneOptions" placeholder="请输入项目" class="input1"
                  v-model="queryParam.projectId"  style="width: 100%;"></a-select>
              </a-form-item> -->
            </a-form-item>
          </a-col>
          <!-- <a-col :xl="5" :lg="8" :md="11" :sm="24">
            <a-form-item label="库房">
              <a-input placeholder="请输入库房" class="input1" v-model="queryParam.warehouseName"></a-input>
            </a-form-item>
          </a-col> -->
          <a-col :xl="4" :lg="6" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <!--              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>-->
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <!-- <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button> -->
           <a-button type="primary" icon="download" @click="handleExportXls('物资记录表')">导出</a-button>
      <!--      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">-->
      <!--        <a-button type="primary" icon="import">导入</a-button>-->
      <!--      </a-upload>-->
      <!--      &lt;!&ndash; 高级查询区域 &ndash;&gt;-->
      <!--      <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>-->
      <!--      <a-dropdown v-if="selectedRowKeys.length > 0">-->
      <!--        <a-menu slot="overlay">-->
      <!--          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>-->
      <!--        </a-menu>-->
      <!--        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>-->
      <!--      </a-dropdown>-->
    </div>

    <!-- table区域-begin -->
    <div>
      <!--      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>-->

      <a-table ref="table" size="middle" bordered rowKey="id" class="j-table-force-nowrap" :scroll="{x:true}"
        :columns="columns" v-bind="tableProps" :dataSource="dataSource" :pagination="ipagination" :loading="loading"
        @change="handleTableChange">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text,record">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" :preview="record.id" height="25px" alt=""
            style="max-width:80px;font-size: 12px;font-style: italic;" />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            下载
          </a-button>
        </template>
        <template slot="inventory" slot-scope="text,record">
          <span>{{text}}</span>
        </template>
        <template slot="inventoryPay" slot-scope="text,record">
          <span>{{text}}</span>
        </template>
        <template slot="inventoryRent" slot-scope="text,record">
          <span>{{text}}</span>
        </template>
        <template slot="action" slot-scope="text, record">
          <a @click="handleEdis(record)"> 详情</a>
          <!-- <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a> 删除</a>
                </a-popconfirm> -->
          <!--          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>-->
        </template>

      </a-table>
    </div>

    <wt-materials-modal ref="modalForm" @ok="modalFormOk" />
  </a-card>
</template>

<script>
  import {
    JeecgListMixin
  } from '@/mixins/JeecgListMixin'
  import WtMaterialsModal from './modules/WtMaterialsModal'
  import '@/assets/less/TableExpand.less'
  import {
    httpAction,
    getAction,
    postAction
  } from '@/api/manage'
  export default {
    name: "WtMaterialsList",
    mixins: [JeecgListMixin],
    components: {
      WtMaterialsModal
    },
    data() {
      return {
        description: '物资记录表管理页面',
        // 表头
        columns: [
          // {
          //   title: '序号',
          //   dataIndex: '',
          //   key:'rowIndex',
          //   width:60,
          //   align:"center",
          //   customRender:function (t,r,index) {
          //     return parseInt(index)+1;
          //   }
          // },
          {
            title: '物资名称',
            align: "center",
            dataIndex: 'platformProductName'
          },
          {
            title: '型号',
            align: "center",
            dataIndex: 'model',

          },
          {
            title: '项目',
            align: "center",
            dataIndex: 'projectName'
          },
          {
            title: '仓库',
            align: "center",
            dataIndex: 'warehouseName'
          },
          {
            title: '总库存',
            align: "center",
            dataIndex: 'inventory',

          },
          {
            title: '入库数',
            align: "center",
            dataIndex: 'inventoryPay',

          },
          {
            title: '出库数',
            align: "center",
            dataIndex: 'inventoryRent',
   
          },
          {
            title: '单位',
            align: "center",
            dataIndex: 'unit',
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: "center",
            fixed: "right",
            width: 147,
            scopedSlots: {
              customRender: 'action'
            },
          }
        ],
        url: {
          list: "/materials/wtMaterials/list",
          delete:'',
          deleteBatch: "/materials/wtMaterials/deleteBatch",
          exportXlsUrl: "/materials/wtMaterials/exportXls",
          importExcelUrl: "materials/wtMaterials/importExcel",

        },
        dictOptions: {},
        superFieldList: [],
        footerDataSource: [],
        levelOneOptions: [],
        is_localstorage:'wzlb', //物资列表-搜索缓存\
		ipagination: {
			current: 1,
			pageSize: 10,
			pageSizeOptions: ['10', '20', '30', '50', '100', '200', '300', '400', '500', '600', '700', '1000'],
			showTotal: (total, range) => {
				return range[0] + '-' + range[1] + ' 共' + total + '条'
			},
			showQuickJumper: true,
			showSizeChanger: true,
			total: 0,
		},
      }
    },
    created() {
      //this.getSuperFieldList();
      this.initDictConfig();
    },
    computed: {
      // 数据表格的固定属性
      tableProps() {
        let tableProps = {
          size: 'middle',
          rowKey: 'rowIndex',
          columns: this.columns,
          scroll: {
            x: true
          },
        }
        let renderFooter = this.footerDataSource.length === 0 ? null : () => this.renderTableFooter(tableProps)
        return {
          ...tableProps,
          ref: 'table',
          class: 'chart-data-list',
          pagination: this.pageSwitch ? this.ipagination : false,
          columns: this.columns,
          dataSource: this.dataSource,
          footer: renderFooter,
        }
      },
      importExcelUrl: function() {
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      }
    },
    methods: {
      tolink(type,record){
        if(!!this.is_localstorage){
            localStorage.setItem(this.is_localstorage,JSON.stringify(this.queryParam));
          }
      },
      handleChange(type, item){
        if (type === 'project') {
          this.queryParam.projectName = item.label;
          this.queryParam.projectId = item.value;
        }
        this.$forceUpdate();
        if(!!this.is_localstorage){
            localStorage.setItem(this.is_localstorage,JSON.stringify(this.queryParam));
        }
      },
      handleEdis(record){
        this.$refs.modalForm.title = '详情';
        this.$refs.modalForm.pageType = 'detail';
        this.$refs.modalForm.edit(record);
        this.$refs.modalForm.disableSubmit = true;
      },
      loadData(arg) {
        if (!this.url.list) {
          this.$message.error("请设置url.list属性!")
          return
        }
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        var params = this.getQueryParams(); //查询条件
        this.loading = true;
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSource = res.result.records || res.result;
            if (res.result.total) {
              this.ipagination.total = res.result.total;
            } else {
              this.ipagination.total = 0;
            }
            this.dataHandling(1, this.ipagination.pageSize, this.dataSource)
            //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.loading = false
        })
      },
      // 渲染表格底部合计行
      renderTableFooter(tableProps) {
        let h = this.$createElement
        return h('a-table', {
          ref: 'footerTable',
          props: {
            ...tableProps,
            pagination: false,
            dataSource: this.footerDataSource,
            showHeader: false,
          },
        })
        //update-end---author:wangshuai ---date:20220209  for：[JTC-494]常用示例->表格合计写法改成新的写法------------
      },
      dataHandling(pageNo, pageSize, dataSource) {
        //根据当前页数和每页显示条数分割数组
        this.newDataSource = dataSource
      
        let arrs = [];
        //如果pageNo不是-1（不分页）,那么需要对数据进行分页计算
        if (pageNo != -1) {
          arrs = this.newDataSource.slice((pageNo - 1) * pageSize, pageNo * pageSize)
        } else {
          arrs = this.newDataSource
        }
        let newDataSource = [];
        let newArr = {};
        newArr.platformProductName = "库存总计";
        let invCount = 0; //库存
        //每一项的数值相加
        for (let j = 0; j < arrs.length; j++) {
          if(!!arrs[j].inventory){
             invCount += parseFloat(arrs[j].inventory);
          }
        }
        newArr.inventory = invCount.toFixed(3);
        newDataSource.push(newArr);
        //给foot底部数组赋值
        this.footerDataSource = newDataSource;
      },
      initDictConfig() {
        getAction(`/sys/sysDepart/getDepartByOrgType?orgType=1`).then((res) => {
          if (res.success) {
        
            this.treeData1 = []
            let treeList1 = res.result
            for (let a = 0; a < treeList1.length; a++) {
              let temp = treeList1[a]
              temp.isLeaf = temp.leaf
              this.treeData1.push(temp)
            }
        
            this.levelOneOptions = [...this.treeData1].map((v) => {
              return {
                ...v,
                value: v.id,
                label: v.departName,
              }
            })
        
        
          }
        })
      },
      getSuperFieldList() {
        let fieldList = [];
        fieldList.push({
          type: 'string',
          value: 'name',
          text: '物资名称',
          dictCode: ''
        })
        fieldList.push({
          type: 'string',
          value: 'model',
          text: '型号',
          dictCode: ''
        })
        fieldList.push({
          type: 'string',
          value: 'inventory',
          text: '库存',
          dictCode: ''
        })
        this.superFieldList = fieldList
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';

  .input1 {
    width: 140px;
    height: 30px;
  }
</style>